<template>
  <div
    ref="audioContext"
    class="audioVisibleContainer"
    :class="props.class"
    :style="props.style"
  >
    <div class="flyChildContainer" v-menus="menus">
      <slot></slot>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted, onUnmounted, watch, nextTick } from "vue";
import AudioVisible from "@/utils/audioVisible";
import { usePlayerStores } from "@/stores/player";
import { debounce } from "@/utils/utils";
import { MenuItemType } from "@/directives/customRightMenu/event";

const menus = ref<{ menus: MenuItemType[]; zIndex: number }>({
  zIndex: 200,
  menus: [
    {
      label: "roundBar",
      click: () => {
        instance.value && instance.value.changeType("roundBar");
      },
    },
    {
      label: "crystal",
      click: () => {
        instance.value && instance.value.changeType("crystal");
      },
    },
  ],
});

const props = defineProps<{
  style?: any;
  class?: string;
  display?: boolean;
}>();

const playerStore = usePlayerStores();
let instance = ref<AudioVisible | null>(null);
const audioContext = ref<null | HTMLElement>(null);

const handleResize = debounce(() => {
  if (instance.value) {
    instance.value.resize();
  }
}, 400);

watch(
  () => props.display,
  (n, o) => {
    if (n === true && !instance.value) {
      if (audioContext.value && playerStore) {
        nextTick(() => {
          instance.value = new AudioVisible(audioContext.value, {
            Type: "roundBar",
            audioNode: playerStore.audio,
          });

          instance.value.init();

          window.addEventListener("resize", handleResize);
        });
      }
    }
  }
);

onUnmounted(() => {
  if (instance.value) {
    instance.value.close();
  }
  window.removeEventListener("resize", handleResize);
});
</script>

<style scoped lang="less">
.audioVisibleContainer {
  width: 340px;
  height: 340px;
  position: relative;
  .flyChildContainer {
    position: absolute;
    top: 20px;
    left: 20px;
    width: 300px;
    height: 300px;
  }
}
</style>
